package JUC_Advanced.chapter2_atomic;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;

/**
 * @Author: GuSongLiao
 * @Date: 2024/3/27 11:26
 * @Description: 原子 字段操作类
 */


class BankAccount {

    private String name = "ICBC";

    private volatile int money = 0;

    public void addMoney() {
        money++;
    }

    public int getMoney() {
        return money;
    }

    public void setMoney(int money) {
        this.money = money;
    }

    AtomicIntegerFieldUpdater updater = AtomicIntegerFieldUpdater.newUpdater(BankAccount.class, "money");

    public void addMoney2() {
        updater.getAndIncrement(this);
    }
}

public class AtomicIntegerFieldUpdaterDemo {

    public static void main(String[] args) throws InterruptedException {

        int size = 10;

        CountDownLatch countDownLatch = new CountDownLatch(size);
        BankAccount bankAccount = new BankAccount();

        for (int i = 0; i < size; i++) {
            new Thread(() -> {
                for (int j = 0; j < 1000; j++) {
//                    bankAccount.addMoney();
                    bankAccount.addMoney2();
                }
                countDownLatch.countDown();
            }, "t1").start();
        }


        System.out.println("=========");
        countDownLatch.await();

        System.out.println("end" + Thread.currentThread().getName() + "%%%%%%%%%%%%%%%     " +  bankAccount.getMoney());

    }


}
